package com.ruoyi.project.api.controller;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.api.config.ALIMessageUtil;
import com.ruoyi.project.api.domain.SendMessage;
import com.ruoyi.project.user.domain.UserInfo;
import com.ruoyi.project.user.service.IUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.AbstractList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @title : SMSController
 * @Author : Administrator
 * @Date : 2025/4/7
 * @Version : 1.0.0
 * @Description : 短信服务
 */
@RestController
@RequestMapping("/api/sms")
public class SMSController {

    private Logger logger = LoggerFactory.getLogger(SMSController.class);
    @Autowired
    private ALIMessageUtil aliMessageUtil;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private IUserInfoService userInfoService;
    @PostMapping("/send")
    public String sendSMS(@RequestBody SendMessage sendMessage) {
        String phoneNumber = sendMessage.getPhoneNumber();
        String message = sendMessage.getMessage();
        String code = RandomUtil.randomNumbers(6);
        logger.info("code: " + code);
        if (phoneNumber!=null&&phoneNumber.length()==11){
//            Map<String, Object> params = new HashMap<>();
//            params.put("code", code);
//            aliMessageUtil.sendMessage(phoneNumber, params);
        }
        redisCache.setCacheObject("sms:" + phoneNumber, code, 10, TimeUnit.MINUTES);
        return "SMS sent to " + phoneNumber + ": " + code;
    }
    @PostMapping("/resign")
    public AjaxResult resignSMS(@RequestBody SendMessage sendMessage) {
        String phoneNumber = sendMessage.getPhoneNumber();
        String code = sendMessage.getCode();
        String redisCode = redisCache.getCacheObject("sms:" + phoneNumber);
        logger.info("redisCode: " + redisCode);
        if (!code.equals(redisCode)) {
            return AjaxResult.error("验证码错误");
        }
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(phoneNumber);
        if (userInfo==null){
            userInfo = new UserInfo();
            userInfo.setUserId(phoneNumber);
            userInfo.setDriverStatus("0");
            userInfo.setDriverContact(phoneNumber);
            userInfoService.insertUserInfo(userInfo);
            return AjaxResult.success(userInfo);
        }

        return AjaxResult.success(userInfo);
    }
}
